﻿//
//  UploadFile.m
//  MyNotification
//
//  Created by zhyuan on 8/24/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UploadFile.h"
#import "JSON.h"

@implementation UploadFile
@synthesize fileData,fileName,serverPath;
@synthesize delegate;
@synthesize message;
@synthesize subjectName;


- (id)initWithDataForReply:(NSString *)url data:(NSData *)data imageName:(NSString*)imageName message:(NSString*)message1
{
	if(self = [super init])
	{
		activeData = [[NSMutableData alloc] init];
		
		self.fileData = data;
		self.fileName = imageName;
		self.serverPath = url;
        self.message = message1;
	}
	return self;
}

- (id)initWithDataForDeliver:(NSString *)url data:(NSData *)data imageName:(NSString*)imageName subjectName:(NSString*)subjectName1 message:(NSString*)message1
{
	if(self = [super init])
	{
		activeData = [[NSMutableData alloc] init];
		
		self.fileData = data;
		self.fileName = imageName;
		self.serverPath = url;
        self.message = message1;
        self.subjectName = subjectName1;
	}
	return self;
}

- (void)dealloc
{
    [subjectName release];
    [message release];
	[fileData release];
	[fileName release];
	[serverPath release];
	
	[activeData release];
	[conn cancel];
	[conn release];
	[super dealloc];
}

- (void)sendReply
{
	NSLog(@"%d",[self.fileData length]);
	//The server header upload file max size is 10M.
	if([self.fileData length] > /*10M*/1024*1024*10)
	{
		[delegate uploadFile:self didUploadFileFailed:@"Max size of file you can upload is 2M"];
	}
	else {
        // setting up the request object now
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        
        // for test
//        UIImage* img = [UIImage imageNamed:@"DSC02819.JPG"];
//        self.fileData = UIImagePNGRepresentation(img);
//        if(self.fileData==nil)
//            self.fileData = UIImageJPEGRepresentation(img,1.0);

//        [request setURL:[NSURL URLWithString:@"http://www.wdfans.cn/mobile/forum.php?mod=post&action=reply&fid=38&tid=95250&authcode=22a9Uc3h4Uq29l/aRHXevRrTL1kVkvBtgZSnygpdMUFtzTzhUqJKFmko2A2PS3SIgbYfNfDw8s7iEE4oO3k7C7u8zd1O_saltkey_77Z1c967&dpdebug=1"]]; 
        
		[request setURL:[NSURL URLWithString:self.serverPath]];
		[request setHTTPMethod:@"POST"];
		/*
		 add some header info now
		 we always need a boundary when we post a file
		 also we need to set the content type
		 
		 You might want to generate a random boundary.. this is just the same
		 as my output from wireshark on a valid html post
		 */
		NSString *boundary = [NSString stringWithString:@"14737809831466499882746641449"];
		NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
		[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
		/*
		 now lets create the body of the post
		 */
		NSMutableData *body = [NSMutableData data];

        
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"replysubmit"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"yes\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"message"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n",self.message] dataUsingEncoding:NSUTF8StringEncoding]]; 
        
        // 带图片
        if (fileData!=nil) {

            [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n\r\n",@"uploadphoto",@"self.fileName"]  dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithData:self.fileData]];
        }
         
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        // setting the body of the post to the reqeust
		[request setHTTPBody:body];
		if(conn != nil)
		{
			[conn cancel];
			[conn release];
		}
		conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	}	
}



- (void)sendDeliver
{
    NSLog(@"%d",[self.fileData length]);
    //The server header upload file max size is 10M.
    if([self.fileData length] > /*10M*/1024*1024*10)
    {
        [delegate uploadFile:self didUploadFileFailed:@"Max size of file you can upload is 2M"];
    }
    else {
    // setting up the request object now
        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    

        [request setURL:[NSURL URLWithString:self.serverPath]];
        [request setHTTPMethod:@"POST"];
    /*
     add some header info now
     we always need a boundary when we post a file
     also we need to set the content type
     
     You might want to generate a random boundary.. this is just the same
     as my output from wireshark on a valid html post
     */
        NSString *boundary = [NSString stringWithString:@"14737809831466499882746641449"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    /*
     now lets create the body of the post
     */
        NSMutableData *body = [NSMutableData data];
    
    
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"topicsubmit"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"true\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
    
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"subject"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n",self.subjectName] dataUsingEncoding:NSUTF8StringEncoding]]; 
        
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"message"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n",self.message] dataUsingEncoding:NSUTF8StringEncoding]]; 
        
    
    // 带图片
        if (fileData!=nil) {
        
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n\r\n",@"uploadphoto",@"self.fileName"]  dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithData:self.fileData]];
        }
    
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
        [request setHTTPBody:body];
        if(conn != nil)
        {
            [conn cancel];
            [conn release];
        }
        conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    }	
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[activeData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[delegate uploadFile:self didUploadFileFailed:@"Upload Failed."];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

	NSString *str = [[[NSString alloc] initWithData:activeData
										   encoding:NSUTF8StringEncoding] autorelease];
	NSLog(@"%@",str);
    
    if ([str length]<10) {
        [delegate uploadFile:self didUploadFileSucceed:@"操作失败"];
    }
    else if([str isEqualToString:@"group_nopermission"])
    {
        [delegate uploadFile:self didUploadFileFailed:@"您的账号还未通过审核"];
        return;
    }
    
//    {"msg":"post_reply_mod_succeed","viewthread_url":"http:\/\/www.wdfans.cn\/mobile\/forum.php?mod=viewthread&tid=1904&page=1&authcode=22a9Uc3h4Uq29l%2FaRHXevRrTL1kVkvBtgZSnygpdMUFtzTzhUqJKFmko2A2PS3SIgbYfNfDw8s7iEE4oO3k7C7u8zd1O_saltkey_77Z1c967"}
    
    
    
    NSDictionary* dict = [str JSONValue];
    NSString* status = [dict objectForKey:@"msg"];
	if([status isEqualToString:@"post_reply_mod_succeed"]||[status isEqualToString:@"post_newthread_mod_succeed"])
	{
		[delegate uploadFile:self didUploadFileFailed:@"发表成功，但需要管理员审核。"];
	}
    else if([str isEqualToString:@"group_nopermission"])
	{
		[delegate uploadFile:self didUploadFileFailed:@"账户未通过审核,无法进行此操作"];
	}
	else {
        
        NSRange r = [status rangeOfString:@"im_post_msg"];
        
        if (r.length>0||[status isEqualToString:@"post_newthread_succeed"]) {
            [delegate uploadFile:self didUploadFileSucceed:@"发表成功"];
        }
        else
            [delegate uploadFile:self didUploadFileFailed:@"操作失败"];
	}
}
@end
